package app.model.proxies
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;

	public class InProxy extends Proxy
	{
		public static const NAME:String = "InProxy";
		
		public static const DATA_IN_LOAD_COMPLETE:String = "dataIn/load/complete";
		public static const DATA_IN_LOAD_FAILURE:String = "dataIn/load/failure";
		public static const DATA_IN_LOAD_PROGRESS:String = "dataIn/load/progress";
		
		private var loader:URLLoader;
		private var request:URLRequest;
		
		public function InProxy()
		{
			super(NAME, []);
		}
		
		public function aquire( url:String ):void{
			loader = new URLLoader(  );
			loader.addEventListener(Event.COMPLETE, onComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			request = new URLRequest( url )
			loader.load( request );
		}		
		
		public function getDataAtURL( url:String ):Object{
			var o:Object = cache[ url ];
			delete cache[ url ];
			return o;
		}
		
		private function setIncomingData(data:Object):void{
			
			cache[request.url] = data;
		}
		
		private function reset():void{
			loader.removeEventListener(Event.COMPLETE, onComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			loader = null;
			//request = null;
		}
		
		private function onComplete(event:Event):void{
			setIncomingData( loader.data );
			
			reset();
			sendCompleteNote( data );
			
		}
		
		private function onError(event:Event):void{
			reset();
			sendFailNote( event );
			
		}
		
		private function onProgress(event:Event):void{
			sendProgressNote( event );
		}
		
		private function sendCompleteNote( data:Object ):void{
			sendNotification(DATA_IN_LOAD_COMPLETE, cache[request.url], request.url);
		}
		
		private function sendFailNote( event:Event ):void{
			sendNotification(DATA_IN_LOAD_FAILURE, event);
		}
		
		private function sendProgressNote( event:Event ):void{
			sendNotification(DATA_IN_LOAD_PROGRESS, event);
		}
		
		private function get cache():Array{
			return data as Array;
		}
		
		
	}
}